package com.mysterymall.Service.Impl;


import com.alibaba.fastjson.JSONObject;
import com.mysterymall.Common.Comp.HttpStatus;
import com.mysterymall.Common.Comp.LocalCache;
import com.mysterymall.Common.Utils.BaseEnum;
import com.mysterymall.Common.Utils.LogUtil;
import com.mysterymall.Common.Utils.Result;
import com.mysterymall.Model.Dto.SmsDto;
import com.mysterymall.Service.SmsService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @ClassName com.mysterymall.Service.Impl
 * @Description
 * @Author HuangWX
 * @Time 2023/12/06  13:52
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Value("${mystery.sms.apiKey}")
    private String apiKey;

    @Value("${mystery.sms.apiSecret}")
    private String apiSecret;

    @Value("${mystery.sms.sendUrl}")
    private String sendUrl;

    @Value("${mystery.sms.verifyUrl}")
    private String verifyUrl;

    @Override
    public Result sendSms(SmsDto smsDto, String sessionId) {

        // 验证码长度
        int codeLength = 4;

        // 过期时间 秒
        int pinExpire = 600;

        // 去除+号
        smsDto.setAreaCode(smsDto.getAreaCode().substring(1));


        OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");

        String requestBodyContent =
                "api_key=" + apiKey
                        + "&api_secret=" + apiSecret
                        + "&to=%2B" + smsDto.getAreaCode() + smsDto.getPhone()
                        + "&code_length=" + codeLength
                        + "&pin_expire=" + pinExpire;

        RequestBody body = RequestBody.create(mediaType, requestBodyContent);

        Request request = new Request.Builder()
                .url(sendUrl)
                .post(body)
                .addHeader("accept", "application/json")
                .addHeader("content-type", "application/x-www-form-urlencoded")
                .build();


        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {

                String jsonString = response.body().string();
                // 处理成功的响应
                log.info("响应数据：" + jsonString);

                JSONObject jsonObject = JSONObject.parseObject(jsonString);
                if (jsonObject.get("request_id") != null) {
                    LocalCache.CACHE.put(BaseEnum.Sms_Code.getCode() + sessionId, jsonObject.get("request_id"), 60 * 1000 * 10);
                    return new Result(HttpStatus.SUCCESS, "message.SmsCont.smsSend.success");
                } else {
                    return new Result(HttpStatus.BAD_NOT_PASS, "message.SmsCont.smsSend.error");
                }
            } else {

                String jsonString = response.body().string();

                JSONObject jsonObject = JSONObject.parseObject(jsonString);

                // 获取错误码、名称和描述
                int errorCode = jsonObject.getJSONObject("error").getIntValue("code");
                String errorName = jsonObject.getJSONObject("error").getString("name");
                String errorDescription = jsonObject.getJSONObject("error").getString("description");

                LogUtil.error("验证码发送失败：区号  " + smsDto.getAreaCode() + "  手机号: " + smsDto.getPhone() + "\n"
                        + "错误码: " + errorCode + "\n"
                        +"错误名称：" + errorName + "\n"
                        +"错误描述：" + errorDescription);

                return new Result(HttpStatus.BAD_NOT_PASS, "message.SmsCont.smsSend.error-" + errorDescription);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new Result(HttpStatus.BAD_NOT_PASS, "message.querySuccess");
    }

    @Override
    public boolean verifySms(String code, String sessionId) throws IOException {

        String request_id = (String) LocalCache.CACHE.get(BaseEnum.Sms_Code.getCode() + sessionId);

        // 判断是否过期
        if (request_id == null) {
            return false;
        }

        // 验证码长度判断
        if(code.length() != 4){
            return false;
        }

        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");

        String requestBodyContent =
                "api_key=" + apiKey
                        + "&api_secret=" + apiSecret
                        + "&request_id=" + request_id
                        + "&code=" + code;

        RequestBody body = RequestBody.create(mediaType, requestBodyContent);

        Request request = new Request.Builder()
                .url(verifyUrl)
                .post(body)
                .addHeader("accept", "application/json")
                .addHeader("content-type", "application/x-www-form-urlencoded")
                .build();

        try (Response response = client.newCall(request).execute()) {
            String jsonString = response.body().string();
            log.info("响应数据：" + jsonString);
            return  response.isSuccessful();
        }
    }
}
